package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    //每分钟执行一次
    @Scheduled(cron = "0 0/1 * * * ?")
    public void payOrderLongTime(){
        LocalDateTime orderTime = LocalDateTime.now().plusMinutes(-15);
        List<Orders> list = orderMapper.findByLongTime(Orders.PENDING_PAYMENT,orderTime);

        if (list==null || list.size()==0){
            return;
        }
        for (Orders order : list){
            order.setStatus(Orders.CANCELLED);
            order.setCancelTime(LocalDateTime.now());
            order.setCancelReason("订单超时未支付");
            orderMapper.update(order);
            log.info("订单号{},已取消",order.getNumber());
        }
    }

    @Scheduled(cron = "0 0 1 * * ?")
    public void processDeliverOrder(){
        //查询所有派送中的订单
        LocalDateTime orderTime = LocalDateTime.now().plusMinutes(-60);
        List<Orders> list = orderMapper.findByLongTime(Orders.DELIVERY_IN_PROGRESS,orderTime);
        if (list==null || list.size()==0){
            return;
        }

        for (Orders order : list){
            order.setStatus(Orders.COMPLETED);
            orderMapper.update(order);
            log.info("订单号{},已完成",order.getNumber());
        }
    }
}
